import java.util.Arrays;

public class 移除元素 {

    public static void main(String[] args) {
        int[] nums = {0,1,2,2,3,0,4,2};
        int val = 2;

        int len = removeElement1(nums, val);
        System.out.println(len);
        System.out.println(Arrays.toString(nums));
    }

    public static int removeElement1(int[] nums, int val) {
        int j = 0;
        int temp = 0;
        int k = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != val) {
                temp = nums[i];
                for (j = i; j > 0 && (nums[j - 1] > temp || nums[j - 1] == val); j--) {
                    nums[j] = nums[j - 1];
                }
                nums[j] = temp;
                k++;
            }
        }
        return k;
    }

    public static int removeElement2(int[] nums, int val) {
        int n = nums.length;
        int left = 0;
        for (int right = 0; right < n; right++) {
            if (nums[right] != val) {
                nums[left] = nums[right];
                left++;
            }
        }
        return left;
    }

    public static int removeElement3(int[] nums, int val) {
        int left = 0;
        int right = nums.length;
        while (left < right) {
            if (nums[left] == val) {
                nums[left] = nums[right - 1];
                right--;
            } else {
                left++;
            }
        }
        return left;
    }


}
